package cn.jietuo.juc.c_007_reentrant;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/6
 * @description: try lock的使用
 * 使用reentrantlock可以进行“尝试锁定”tryLock，这样无法锁定，或者在指定时间内无法锁定，线程可以决定是否继续等待
 * 如果不做任何处理，线程就会继续往下面执行
 */
public class T02_ReentrantLock {

    private ReentrantLock lock = new ReentrantLock();

    private void m1() {
        try {
            lock.lock();
            try {
                System.out.println("m1 start");
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } finally {
            lock.unlock();
        }
    }

    private void m2() {
        boolean locked = false;
        try {
            locked = lock.tryLock(4, TimeUnit.SECONDS);
            System.out.println(Thread.currentThread().getName() + "，m2...locked:" + locked);
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "---" + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();

        } finally {
            if (locked) {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        T02_ReentrantLock t = new T02_ReentrantLock();
        new Thread(t::m1).start();
        new Thread(t::m2).start();
        // 此线程没有锁定m2
        new Thread(t::m2).start();

    }


}
